import axios from 'axios'
import config from '@/config/index.js'
import { isArray, isObject, isEmpty } from "@/utils/object";
import {$get} from '@/puigins/request.js'
const paramsSerializer = (data) => {
    if (isObject(data)) {
        let arr = []
        for (let key in data) {
            try {
                if (isObject(data[key]) || isArray(data[key])) {
                    arr.push(`${key}=${encodeURI(JSON.stringify(data[key]))}`)
                } else {
                    arr.push(`${key}=${encodeURI(data[key])}`)
                }
            } catch (e) { }

        }
        return arr.join("&")
    } else {
        return JSON.stringify(data)
    }
}
axios.defaults.baseURL = config.URL
axios.defaults.paramsSerializer = paramsSerializer
axios.defaults.headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
}

export function loginByUsername(form) {
    return axios({
        url: '/user/userLogin',
        method: 'POST',
        data: paramsSerializer(form)
    })
}

export function requestRegisterYzm(form) {
    return axios({
        url: '/user/requestRegisterYzm',
        method: 'POST',
        data: paramsSerializer(form)
    })
}
export function register(form) {
    return axios({
        url: '/user/registerUser',
        method: 'POST',
        data: paramsSerializer(form)
    })
}
export function qqLogin(openId, accessToken) {
    return axios({
        url: '/user/qqLogin',
        method: 'POST',
        data: paramsSerializer({
            openId, accessToken
        })
    })
}
export function autoLogin() {
	return new Promise((resolve, reject) => {
		$get('/user/autoLogin', null, {
			headers: {
				Authorization: window.localStorage.getItem("authorization")
			}
		}).then(({ data }) => {
			resolve(data)
		}).catch(reject)
	})
}